package net.wanho.servlet;

import com.alibaba.fastjson.JSON;
import net.wanho.entity.User;
import net.wanho.util.AjaxResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Author：汤小洋
 * Date：2024-07-29 11:28
 * Description：<描述>
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // MIME类型
        // resp.setContentType("text/plain;charset=utf8"); // 响应简单的字符串
        resp.setContentType("application/json;charset=utf8"); // 响应简单的字符串
        PrintWriter out = resp.getWriter();

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        AjaxResult result = new AjaxResult();
        if("admin".equals(username) && "123".equals(password)){
            /**
             * 将对象转换为json字符串
             */
            User user = new User(1,"admin","123",18,"男",180.5,new Date());
            // String str = JSON.toJSONString(user); // 将对象转换为json字符串
            // System.out.println(str);

            // List<User> list = new ArrayList<>();
            // list.add(new User(1,"admin","123",18,"男",180.5,new Date()));
            // list.add(new User(2,"tom","123",18,"男",180.5,new Date()));
            // list.add(new User(3,"jack","123",18,"男",180.5,new Date()));
            // out.print(JSON.toJSONString(list));


            /**
             * 将json字符串转换为对象
             */
            // User user = new User(1,"admin","123",18,"男",180.5,new Date());
            // String str = JSON.toJSONString(user); // 将对象转换为json字符串
            //
            // User u = JSON.parseObject(str, User.class);
            // System.out.println(u);

            // System.out.println(str);

            /**
             * 自定义响应结果对象
             */
            result.setStatus(200);
            result.setMsg("登录成功");
            result.setData(user);
        }else{
            result.setStatus(500);
            result.setMsg("用户名或密码错误");
        }
        out.print(JSON.toJSONString(result));
        out.close();
    }


}
